package com.nativetalk.service.teacher.register;

import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.FoundChange.TdNtTeaFoundChangeInsert;
import com.nativetalk.bean.TdNtTeaInvitation;
import com.nativetalk.bean.email.EmailUtil;
import com.nativetalk.bean.teacher.TdNtTeacherRegister;
import com.nativetalk.bean.teacher.TdNtTeacherResult;
import com.nativetalk.bean.website.TsNtWebSiteConfIndex;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.util.*;
import com.nativetalk.dao.TdNtTeaFoundChangeDao;
import com.nativetalk.dao.TdNtTeacherDao;
import com.tls.tls_sigature.tls_sigature;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by lizhun on 16/1/7.
 */
@Service
public class TeacherRegisterServiceImpl implements  TeacherRegisterService {
    private static Logger logger = Logger.getLogger(TeacherRegisterServiceImpl.class);
    @Resource
    private TdNtTeacherDao tdNtTeacherDao;
    @Resource
    private TdNtTeaFoundChangeDao tdNtTeaFoundChangeDao;
    @Override
    public RetInfo sendEmail(EmailUtil emailUtil) {
        String logInfo = this.getClass().getName() + ":sendEmail:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            TdNtTeacherResult tdNtTeacherResult = tdNtTeacherDao.findTdNtTeacherResult(emailUtil.getTea_email());
            if (tdNtTeacherResult != null){
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("TEARCHER.REUSLT.SUCCESS"));
                logger.info("用户已存在 email=" + emailUtil.getTea_email());

            } else {
                String register = "register" + emailUtil.getTea_email();
                String sencod = "sencod" + emailUtil.getTea_email();// 60秒内是否已经发送过email
                if (!("0".equals(MemcachedUtils.get(sencod)))) {
                    String code = SmsCodeUtil.getSmsCode();
                    logger.info("发送邮件：" + emailUtil.getTea_email() + ",验证码：" + code);
                    String result = SendMail.sendMail(emailUtil.getTea_email(),code);

                    if (result.equals("0")){
                        logger.info("发送邮件成功：" + emailUtil.getTea_email() + ",验证码：" + code);
                        retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                        retInfo.setTip(ValidationMessages.getValue("SEND.EMAIL.SUCCESS"));
                        if (MemcachedUtils.get(register) == null){
                            MemcachedUtils.add(register,code,5*60);
                            logger.info("缓存中 新增 验证码,key:" + register + ",value(code):" + code);
                        }else{
                            MemcachedUtils.replace(register,code,5*60);
                            logger.info("缓存中 更新 验证码,key:" + register + ",value(code):" + code);
                        }
                        MemcachedUtils.add(sencod, "0",60);
                    } else {
                        logger.info("发送邮件失败：" + emailUtil.getTea_email() + ",验证码：" + code);
                        retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                        retInfo.setTip(ValidationMessages.getValue("SEND.EMAIL.ERROR"));
                    }
                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("SEND.EMAIL.OVER"));
                }

            }

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo register(TdNtTeacherRegister tdNtTeacherRegist) {
        String logInfo = this.getClass().getName() + ":register:";
        logger.info("======" + logInfo + "begin======");
        Date now = new Date();
        RetInfo retInfo = new RetInfo();
        try {
            TdNtTeacherResult tdNtTeacherResult = tdNtTeacherDao.findTdNtTeacherResult(tdNtTeacherRegist.getTea_email());
            if (tdNtTeacherResult != null){

                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("TEARCHER.REUSLT.SUCCESS"));

            } else {
                String register = "register" + tdNtTeacherRegist.getTea_email();
                if (tdNtTeacherRegist.getCode().equals(MemcachedUtils.get(register))){
                    TdNtTeacherRegister tdNtTeacherRegister = new TdNtTeacherRegister();
                    tdNtTeacherRegister.setEqu_type(tdNtTeacherRegist.getEqu_type());
                    tdNtTeacherRegister.setEqu_client_id(tdNtTeacherRegist.getEqu_client_id());
                    if (tdNtTeacherRegist.getInvite_code() != null){
                        TdNtTeacherResult tdNtTeacherResultCode = tdNtTeacherDao.findTdNtTeacherResultByCode(tdNtTeacherRegist.getInvite_code());
                        if (tdNtTeacherResultCode != null) {
                            /**
                             * 判断教师邀请码邀请的人数
                             */
                            Map<String , TsNtWebSiteConfIndex> tsNtWebSiteConfIndexMap = (Map<String , TsNtWebSiteConfIndex>)MemcachedUtils.get(MemcachedKey.tsNtWebSiteConfIndexMap);

                            Integer tea_reward_limit = Integer.valueOf(tsNtWebSiteConfIndexMap.get("23").getData_value());
                            Integer tea_cover_int_reward = Integer.valueOf(tsNtWebSiteConfIndexMap.get("22").getData_value());
                            if (tea_reward_limit.equals(0)) {
                                //添加教师信息

                                tdNtTeacherRegister.setTea_islock("4");
                                tdNtTeacherRegister.setTea_invite_code(CommonUtil.getInviteCode());
                                tdNtTeacherRegister.setTea_register_month(CommonUtil.getMonth(now));
                                tdNtTeacherRegister.setTea_birthday(new Timestamp(new Date().getTime()));
                                tdNtTeacherRegister.setTea_password(MD5.code(tdNtTeacherRegist.getTea_password()));
                                tdNtTeacherRegister.setTea_score(new BigDecimal("5"));
                                tdNtTeacherRegister.setTea_sex("1");
                                tdNtTeacherRegister.setToken(CommonUtil.getToken());
                                tdNtTeacherRegister.setTea_balance(new BigDecimal(tea_cover_int_reward));
                                tdNtTeacherRegister.setTea_email(tdNtTeacherRegist.getTea_email());
                                tdNtTeacherRegister.setTea_head_portrait("/nativetalk/head/head_teacher.png");
                                tdNtTeacherRegister.setState(Constants.Teacher.State.offline);
                                tdNtTeacherRegister.setState_order(Constants.Teacher.StateOrder.offline);
                                tdNtTeacherRegister.setTea_total_balance(new BigDecimal("0"));
                                tdNtTeacherRegister.setTea_times(0);
                                tdNtTeacherRegister.setTea_name("NativeTalk");
                                tdNtTeacherRegister.setUid(UUID.randomUUID().toString());
                                tdNtTeacherDao.insertTdNtTeacher(tdNtTeacherRegister);
                                /**
                                 * 插入邀请的记录
                                 */
                                Timestamp date = new Timestamp(System.currentTimeMillis());

                                TdNtTeaInvitation tdNtTeaInvitation = new TdNtTeaInvitation();
                                tdNtTeaInvitation.setInt_tea_id(tdNtTeacherResultCode.getTea_id());
                                tdNtTeaInvitation.setCover_int_tea_id(tdNtTeacherRegister.getTea_id());
                                tdNtTeaInvitation.setRegister_time(date);
                                tdNtTeaInvitation.setRegister_month(CommonUtil.getMonth(now));
//                                tdNtTeaInvitation.setInt_reward(new BigDecimal("2"));
                                tdNtTeaInvitation.setCover_int_reward(new BigDecimal(tea_cover_int_reward));
                                tdNtTeacherDao.insertInvit(tdNtTeaInvitation);
                                if (!tea_cover_int_reward.equals(0)) {
                                    TdNtTeaFoundChangeInsert tdNtTeaFoundChangeInsertRegister = new TdNtTeaFoundChangeInsert();
                                    tdNtTeaFoundChangeInsertRegister.setState("2");
                                    tdNtTeaFoundChangeInsertRegister.setTea_id(tdNtTeacherRegister.getTea_id());
                                    tdNtTeaFoundChangeInsertRegister.setTfchg_account(new BigDecimal(tea_cover_int_reward));
                                    tdNtTeaFoundChangeInsertRegister.setTfchg_back_amount(new BigDecimal(tea_cover_int_reward));
                                    tdNtTeaFoundChangeInsertRegister.setTfchg_change_amount(new BigDecimal(tea_cover_int_reward));
                                    tdNtTeaFoundChangeInsertRegister.setTfchg_change_month(CommonUtil.getMonth(now));
                                    tdNtTeaFoundChangeInsertRegister.setTfchg_change_type("1");
                                    tdNtTeaFoundChangeInsertRegister.setTfchg_counter_fee(new BigDecimal("0"));
                                    tdNtTeaFoundChangeInsertRegister.setTfchg_front_amount(new BigDecimal("0"));
                                    tdNtTeaFoundChangeInsertRegister.setTfchg_number(CommonUtil.getOrderNub());
                                    tdNtTeaFoundChangeInsertRegister.setTfchg_change_name("Registration bonus");
                                    tdNtTeaFoundChangeInsertRegister.setType(3);
                                    tdNtTeaFoundChangeDao.insertTdNtTeaFoundChangeInsert(tdNtTeaFoundChangeInsertRegister);
                                }


                            } else {
                                int size = tdNtTeacherDao.findInviteSize(tdNtTeacherResultCode.getTea_id());
                                if (size <= tea_reward_limit) {
                                    //添加教师信息
                                    tdNtTeacherRegister.setTea_islock("4");
                                    tdNtTeacherRegister.setTea_invite_code(CommonUtil.getInviteCode());
                                    tdNtTeacherRegister.setTea_register_month(CommonUtil.getMonth(now));
                                    tdNtTeacherRegister.setTea_birthday(new Timestamp(new Date().getTime()));
                                    tdNtTeacherRegister.setTea_password(MD5.code(tdNtTeacherRegist.getTea_password()));
                                    tdNtTeacherRegister.setTea_score(new BigDecimal("5"));
                                    tdNtTeacherRegister.setTea_sex("1");
                                    tdNtTeacherRegister.setToken(CommonUtil.getToken());
                                    tdNtTeacherRegister.setTea_balance(new BigDecimal(tea_cover_int_reward));
                                    tdNtTeacherRegister.setTea_email(tdNtTeacherRegist.getTea_email());
                                    tdNtTeacherRegister.setTea_head_portrait("/nativetalk/head/head_teacher.png");
                                    tdNtTeacherRegister.setState(Constants.Teacher.State.offline);
                                    tdNtTeacherRegister.setState_order(Constants.Teacher.StateOrder.offline);
                                    tdNtTeacherRegister.setTea_total_balance(new BigDecimal("0"));
                                    tdNtTeacherRegister.setTea_times(0);
                                    tdNtTeacherRegister.setTea_name("NativeTalk");
                                    tdNtTeacherRegister.setUid(UUID.randomUUID().toString());
                                    tdNtTeacherDao.insertTdNtTeacher(tdNtTeacherRegister);
                                    /**
                                     * 插入邀请的记录
                                     */
                                    Timestamp date = new Timestamp(System.currentTimeMillis());

                                    TdNtTeaInvitation tdNtTeaInvitation = new TdNtTeaInvitation();
                                    tdNtTeaInvitation.setInt_tea_id(tdNtTeacherResultCode.getTea_id());
                                    tdNtTeaInvitation.setCover_int_tea_id(tdNtTeacherRegister.getTea_id());
                                    tdNtTeaInvitation.setRegister_time(date);
                                    tdNtTeaInvitation.setRegister_month(CommonUtil.getMonth(now));
//                                tdNtTeaInvitation.setInt_reward(new BigDecimal("2"));
                                    tdNtTeaInvitation.setCover_int_reward(new BigDecimal(tea_cover_int_reward));
                                    tdNtTeacherDao.insertInvit(tdNtTeaInvitation);

                                    // 如果有注册奖金，插入资金记录
                                    if (!tea_cover_int_reward.equals(0)) {
                                        TdNtTeaFoundChangeInsert tdNtTeaFoundChangeInsertRegister = new TdNtTeaFoundChangeInsert();
                                        tdNtTeaFoundChangeInsertRegister.setState("2");
                                        tdNtTeaFoundChangeInsertRegister.setTea_id(tdNtTeacherRegister.getTea_id());
                                        tdNtTeaFoundChangeInsertRegister.setTfchg_account(new BigDecimal(tea_cover_int_reward));
                                        tdNtTeaFoundChangeInsertRegister.setTfchg_back_amount(new BigDecimal(tea_cover_int_reward));
                                        tdNtTeaFoundChangeInsertRegister.setTfchg_change_amount(new BigDecimal(tea_cover_int_reward));
                                        tdNtTeaFoundChangeInsertRegister.setTfchg_change_month(CommonUtil.getMonth(now));
                                        tdNtTeaFoundChangeInsertRegister.setTfchg_change_type("1");
                                        tdNtTeaFoundChangeInsertRegister.setTfchg_counter_fee(new BigDecimal("0"));
                                        tdNtTeaFoundChangeInsertRegister.setTfchg_front_amount(new BigDecimal("0"));
                                        tdNtTeaFoundChangeInsertRegister.setTfchg_number(CommonUtil.getOrderNub());
                                        tdNtTeaFoundChangeInsertRegister.setTfchg_change_name("Registration bonus");
                                        tdNtTeaFoundChangeInsertRegister.setType(3);
                                        tdNtTeaFoundChangeDao.insertTdNtTeaFoundChangeInsert(tdNtTeaFoundChangeInsertRegister);
                                    }
                                }else{
                                    tdNtTeacherRegister.setTea_balance(new BigDecimal("0.00"));
                                    //添加教师信息
                                    tdNtTeacherRegister.setTea_islock("4");
                                    tdNtTeacherRegister.setTea_invite_code(CommonUtil.getInviteCode());
                                    tdNtTeacherRegister.setTea_register_month(CommonUtil.getMonth(now));
                                    tdNtTeacherRegister.setTea_birthday(new Timestamp(new Date().getTime()));
                                    tdNtTeacherRegister.setTea_password(MD5.code(tdNtTeacherRegist.getTea_password()));
                                    tdNtTeacherRegister.setTea_score(new BigDecimal("5"));
                                    tdNtTeacherRegister.setTea_sex("1");
                                    tdNtTeacherRegister.setToken(CommonUtil.getToken());
                                    tdNtTeacherRegister.setTea_email(tdNtTeacherRegist.getTea_email());
                                    tdNtTeacherRegister.setTea_head_portrait("/nativetalk/head/head.png");
                                    tdNtTeacherRegister.setState(Constants.Teacher.State.offline);
                                    tdNtTeacherRegister.setState_order(Constants.Teacher.StateOrder.offline);
                                    tdNtTeacherRegister.setTea_total_balance(new BigDecimal("0"));
                                    tdNtTeacherRegister.setTea_times(0);
                                    tdNtTeacherRegister.setTea_name("NativeTalk");
                                    tdNtTeacherRegister.setUid(UUID.randomUUID().toString());
                                    tdNtTeacherDao.insertTdNtTeacher(tdNtTeacherRegister);
                                }

                            }

                        } else {
                            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                            retInfo.setTip(ValidationMessages.getValue("TEACHER.INVITE.CODE.NULL"));
                            return retInfo;
                        }

                    } else {
                        tdNtTeacherRegister.setTea_balance(new BigDecimal("0.00"));
                        //添加教师信息
                        tdNtTeacherRegister.setTea_islock("4");
                        tdNtTeacherRegister.setTea_invite_code(CommonUtil.getInviteCode());
                        tdNtTeacherRegister.setTea_register_month(CommonUtil.getMonth(now));
                        tdNtTeacherRegister.setTea_birthday(new Timestamp(new Date().getTime()));
                        tdNtTeacherRegister.setTea_password(MD5.code(tdNtTeacherRegist.getTea_password()));
                        tdNtTeacherRegister.setTea_score(new BigDecimal("5"));
                        tdNtTeacherRegister.setTea_sex("1");
                        tdNtTeacherRegister.setToken(CommonUtil.getToken());
                        tdNtTeacherRegister.setTea_email(tdNtTeacherRegist.getTea_email());
                        tdNtTeacherRegister.setTea_head_portrait("/nativetalk/head/head.png");
                        tdNtTeacherRegister.setState(Constants.Teacher.State.offline);
                        tdNtTeacherRegister.setState_order(Constants.Teacher.StateOrder.offline);
                        tdNtTeacherRegister.setTea_total_balance(new BigDecimal("0"));
                        tdNtTeacherRegister.setTea_times(0);
                        tdNtTeacherRegister.setTea_name("NativeTalk");
                        tdNtTeacherRegister.setUid(UUID.randomUUID().toString());
                        tdNtTeacherDao.insertTdNtTeacher(tdNtTeacherRegister);
                    }
                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip(ValidationMessages.getValue("TEACHER.REGISTER.SUCCESS"));
                    Map<String,Object> map = new HashMap<>();
                    map.put("token",tdNtTeacherRegister.getToken());
                    map.put("sig", tls_sigature.getUsersig(Constants.teacher + tdNtTeacherRegister.getTea_id()));
                    map.put("lock",tdNtTeacherRegister.getTea_islock());
                    map.put("Identifier", Constants.teacher + tdNtTeacherRegister.getTea_id());
                    map.put("uid", tdNtTeacherRegister.getUid());
                    retInfo.setObj(map);

                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("TEACHER.INVITE.CODE.ERROR"));
                }
            }

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    static String appId = Constants.teacher_appId;
    static String appKey = Constants.teacher_appKey;
    static String masterSecret = Constants.teacher_masterSecret;
    static String url = Constants.getui_url;
    //使用https的域名
    //static String url = "https://api.getui.com/apiex.htm";
    public static void apnpush(String title,String body,String devicetoken)  {
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setTransmissionType(2);        //应用启动类型，1：强制应用启动 2：等待应用启动

        //    template.setTransmissionContent(stt_id+"");  //透传内容


        //APN高级推送
        APNPayload apnpayload = new APNPayload();
        APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
        alertMsg.setBody(body);
        //IOS8.2支持字段
        alertMsg.setTitle(title);

        apnpayload.setAlertMsg(alertMsg);
        apnpayload.setContentAvailable(2);//透传数据
        template.setAPNInfo(apnpayload);

        IGtPush push = new IGtPush(url, appKey, masterSecret);


        SingleMessage message = new SingleMessage();
        message.setData(template);

        IPushResult pushResult = push.pushAPNMessageToSingle(appId,devicetoken,message);

    }
}
